package com.openweixin.sheknows.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.openweixin.sheknows.common.Pager;
import com.openweixin.sheknows.domain.Question;
import com.openweixin.sheknows.service.QuestionService;
import com.openweixin.sheknows.service.UserNewAnswerService;
import com.openweixin.sheknows.util.SessionUtil;
@Controller
@RequestMapping("/question")
public class QuestionController extends BaseController{

	@Autowired
	private QuestionService service;
	@Autowired
	private UserNewAnswerService unaService;
	
	@RequestMapping
	public String toMain(){
		return "Question";
	}
	
	@RequestMapping("/listView")
	public String listView(Pager<Question> pager){
		pager.setSort("datetime");
		pager.setLimit(5);
		Integer uid=SessionUtil.getUserID();
		pager = service.findQuestionPagerByUser(pager, uid);
		return "question/listView";
	}
	
	@RequestMapping("/details")
	public ModelAndView questionDetails(@RequestParam Integer id){
		Question question=service.readQuestionById(id);
		unaService.deleteByUid(getLoginUser().getUid());
		return new ModelAndView("question/details","question",question);
	}

	@RequestMapping("/list")
	public Pager<Question> list(Pager<Question> pager){
		pager.setSort("datetime");
		Integer uid=SessionUtil.getUserID();
		pager = service.findQuestionPagerByUser(pager, uid);
		return pager;
	}

	@RequestMapping("/add")
	@ResponseBody 
	public String add( Question bean){
		try {
			bean.setUser(getLoginUser());
			bean.setStatus(0);
			service.save(bean);
			return SUCCESS;
		} catch (Exception e) {
			return FAIL;
		}
	}

	@RequestMapping("/update")
	@ResponseBody 
	public String update(@RequestBody Question bean){
		service.update(bean);
		return SUCCESS; 
	}

	@RequestMapping("/delete")
	@ResponseBody 
	public String delete(Integer[] ids){
		service.delete(ids);
		return SUCCESS; 
	}

	@RequestMapping("/newQuestion")
	public String newQuestion(){
		return "question/new_question"; 
	}
	
	@RequestMapping("/reSubmit")
	@ResponseBody
	public String reSubmit(Integer id){
		
		Integer uid=SessionUtil.getUserID();
		if(service.reSubmit(id,uid))
			return SUCCESS;
		return FAIL;
	}
}
